#ifndef CA64F7AB_6899_416D_976E_D3BCCC0E309C
#define CA64F7AB_6899_416D_976E_D3BCCC0E309C

#endif /* CA64F7AB_6899_416D_976E_D3BCCC0E309C */

#include "head.h"
#include "Log.hpp"

typedef function<string(const string&)> func_t;

Log lg;

uint16_t defaultport = 8080;
string defaultip = "0.0.0.0";
const int size = 1024;

enum{
    SOCKET_ERR = 1,
    BIND_ERR
};

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport, const string& ip = defaultip)
        :sockfd_(0), ip_(ip), port_(port), isrunning_(false)
    {}

    void Init()
    {   
        // 1.创建udp socket套接字
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd: %d",sockfd_);

        // 2.bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = inet_addr(ip_.c_str());

        if(bind(sockfd_, (const sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind err, errnoL %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success");
    }

    void Run(func_t func)
    {
        isrunning_ = true;
        char inbuffer[size];
        while(isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer)-1, 0, (sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom errno, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            string info = inbuffer;
            // cout << "get a message: " << info << endl;
            string e_string = func(info);
            sendto(sockfd_, e_string.c_str(), e_string.size(), 0, (const sockaddr*)&client, len);
        }
    }

    ~UdpServer()
    {
        if(sockfd_ > 0)
            close(sockfd_);
    }

private:
    int sockfd_;        // 网路文件描述符
    string ip_;         // 任意地址bind ->0
    uint16_t port_;     // 表明服务器进程的端口号
    bool isrunning_;    // 服务器是否正在运行
};